// ----------------------- 获取学员数据 -------------------------
function renderStudent() {
    axios.get('/student/list').then(res => {
        const { code, data } = res.data
        if (code === 0) {
            let arr = [];
            data.forEach(item => {
                arr.push(`
          <tr>
              <th scope="row">${item.id}</th>
              <td>${item.name}</td>
              <td>${item.age}</td>
              <td>${item.sex}</td>
              <td>${item.group}</td>
              <td>${item.phone}</td>
              <td>${item.salary}</td>
              <td>${item.truesalary}</td>
              <td>${item.province}${item.city}${item.county}</td>
              <td>
              <button data-id="${item.id}" type="button" class="btn btn-primary btn-sm update">修改</button>
              <button data-id="${item.id}" type="button" class="btn btn-danger btn-sm del">删除</button>
              </td>
          </tr>
          `);
            });
            qs('tbody').innerHTML = arr.join('')
        }
    })
}
renderStudent();

// ----------------------- 添加显示弹层 --------------------------
qs('#addBtn').onclick = function() {
    qs('#addModal').classList.add('show')
    qs('#backdrop').classList.add('show')
}
qs('#closeAddBtn').onclick = function() {
    qs('#addModal').classList.remove('show')
    qs('#backdrop').classList.remove('show')
}

qs('#closeUpdateBtn').onclick = function() {
    qs('#updateModal').classList.remove('show')
    qs('#backdrop').classList.remove('show')
}

// --------------------- 获取省 ---------------------
axios.get('/geo/province').then(({ data }) => {
    let arr = ['<option selected value="">--省--</option>'];
    data.forEach(item => {
        arr.push(`<option value="${item}">${item}</option>`)
    });
    qsAll('select[name=province]').forEach(item => item.innerHTML = arr.join(''))
})

// --------------------- 省切换的时候，选择市 ---------------------
qsAll('select[name=province]').forEach((select, i) => {
    console.log('----select----', select, i);
    select.onchange = function() {
        // 重置县
        qsAll('select[name=county]')[i].innerHTML = `<option selected value="">--县--</option>`
        let pname = this.value;
        axios.get('/geo/city', { params: { pname } }).then(({ data }) => {
            let arr = ['<option selected value="">--市--</option>'];
            data.forEach(item => {
                arr.push(`<option value="${item}">${item}</option>`)
            });
            qsAll('select[name=city]')[i].innerHTML = arr.join('')
        })
    }
})

// --------------------- 市切换的时候，选择县 ---------------------
qsAll('select[name=city]').forEach((select, i) => {
    select.onchange = function() {
        let pname = qsAll('select[name=province]')[i].value
        let cname = this.value;
        axios.get('/geo/county', { params: { pname, cname } }).then(({ data }) => {
            let arr = ['<option selected value="">--县--</option>'];
            data.forEach(item => {
                arr.push(`<option value="${item}">${item}</option>`)
            });
            qsAll('select[name=county]')[i].innerHTML = arr.join('')
        })
    }
})


// -------------------- 添加完成 ----------------------------------
qs('.add-form').onsubmit = function(e) {
    e.preventDefault()
    const formObj = seralizeForm('.add-form')
    axios.post('/student/add', formObj).then(res => {
        const { code, message } = res.data
        if (code === 0) {
            alert(message)
            renderStudent();
            // 关闭模态框
            qs('#addModal').classList.remove('show')
            qs('#backdrop').classList.remove('show')
        }
    })
}

// ----------------------- 修改显示弹层 --------------------------
// 修改学员 / 删除学员(事件委托)
qs('tbody').onclick = function(e) {
    if (e.target.classList.contains('update')) {
        let id = e.target.dataset.id
        axios.get('/student/one', { params: { id } }).then((res) => {
            const { code, data } = res.data
            if (code === 0) {
                let { name, age, sex, group, phone, id, salary, truesalary, province, city, county } = data;
                // 回显数据
                qs('#updateModal input[name=id]').value = id
                qs('#updateModal input[name=name]').value = name
                qs('#updateModal input[name=age]').value = age
                qs('#updateModal input[name=sex][value=' + sex + ']').checked = true
                qs('#updateModal input[name=phone]').value = phone
                qs('#updateModal input[name=salary]').value = salary
                qs('#updateModal input[name=truesalary]').value = truesalary
                qs('#updateModal select[name=group]').value = group;
                qs('#updateModal select[name=province]').value = province
                qs('#updateModal select[name=city]').innerHTML = `<option value="${city}">${city}</option>`
                qs('#updateModal select[name=county]').innerHTML = `<option value="${county}">${county}</option>`

                // 让模态框显示
                qs('#updateModal').classList.add('show')
                qs('#backdrop').classList.add('show')
            }
        })
    }

    if (e.target.classList.contains('del')) {
        if (!confirm('你确定要删除吗？')) return;
        let id = e.target.dataset.id
        axios.delete('/student/delete', { params: { id } }).then(res => {
            const { code, message } = res.data
            if (code === 0) {
                alert(message)
                renderStudent()
            }
        })
    }
}

// qs('.btn-close').onclick = function (e) {
//   e.preventDefault();
//   // console.log(11);
//   qs('#updateModal').classList.remove('show')
//   qs('#backdrop').classList.remove('show')
// }

// ------------------------- 修改学员 - 确认修改 ----------------------------
qs('.update-form').onsubmit = function(e) {
    e.preventDefault();
    //提交逻辑
    let dataObj = seralizeForm('.update-form');
    axios.put('/student/update', dataObj).then(res => {
        const { message, code } = res.data
        if (code === 0) {
            alert(message)
            renderStudent();
            qs('#updateModal').classList.remove('show')
            qs('#backdrop').classList.remove('show')
        }
    })
}